<template>
  <div id="photo-app">
    <!-- 选择照片的input，type=file 隐藏起来等待触发就好 -->
    <input 
      type="file" id="fileInput" 
      name="file" 
      style="display:none;" 
      ref="fileInput"
    />
    <div class="nav-bar" >
        <span class="nav-bar-left" >
          <van-icon name="wap-home" @click="toHome" />
        </span>
        <span class="nav-bar-right">
          <!-- <i class="iconfont nav-icon">&#xe601;</i> -->
          <span  @click="selectNewPhoto">打开</span>
          <span @click="checkImg">
            <van-icon name="label" style="padding-top:3px; vertical-align: -2px; margin:0 5px 0 15px;" />上传记录
          </span>
        </span>
    </div>

    <van-dialog
      v-model="exportShow"
      title="上传记录"
      show-cancel-button
      confirm-button-text="下载"
      cancel-button-text="关闭"
      @confirm="download(imgInfo.imgUrl,'png',imgInfo.usename+'_'+imgInfo.useID)"
      @cancel="exportShow = false"
      :style="{ width : '92vw' }"
    >
      <div class="index-img-box">
        <div class="index-img-info">
          <div>{{ imgInfo.useID }}</div>
          <div>{{ imgInfo.usename }}</div>
          <div>{{ imgInfo.grade }}级</div>
          <div>{{ imgInfo.college }}</div>
        </div>
        <img :src="imgInfo.imgUrl" alt="" class="index-img">
      </div>
    </van-dialog>

    <select-photo @selectPhoto="selectNewPhoto" v-if="isSelectHome"></select-photo>
    <router-view/>
  </div>
</template>

<script>
import SelectPhoto from "./components/SelectPhoto"
import Vue from 'vue';
import { Icon } from 'vant';
import { Dialog } from 'vant';

Vue.use(Icon);
Vue.use(Dialog)

export default {
  components : {
    SelectPhoto,
  },
  data () {
    return {
      isSelectHome : true,
      imageSrc : '',
      hasPhoto : false,
      exportShow : false,
      imgInfo : {
        imgUrl : '',
        college : '',
        grade : '',
        useID : '',
        usename : ''
      }
    }
  },
  methods: {
    selectNewPhoto() {
      // 监听是否有选择文件
      let self = this;
      this.$refs.fileInput.value = '';
      this.$refs.fileInput.onchange = function(e){
        try {
          self.imageSrc = URL.createObjectURL(e.target.files[0]);
          if(self.imageSrc){
            self.$store.state.imgSrc = self.imageSrc;  // 存储到仓库
            self.isSelectHome = false;
            if(self.$route.name == 'Crop'){
              self.$store.state.imgSrc = self.imageSrc;  // 存储到仓库
            }else{
              self.$router.push({
              name : "Crop", //路由配置中的name
            });
            }
          }
        }catch (err){
          console.log(err,'未选择照片');
        }
      }
      this.$refs.fileInput.click(); // 选择照片
    },
    toHome() {
      this.$router.push('/record')
    },
    checkImg() {
      let userId = this.$store.state.userId;
      let url = `${this.$api}getInformation/download/${userId}`
      this.$axios.get(url).then(res => {
        console.log(res)
        if(res.data.code === 5000){
          return this.$toast({
            message: '您暂未上传过证件照'
          })
        }
        let { data } = res
        this.imgInfo.imgUrl = 'data:image/png;base64,' + data.imgSrc
        this.imgInfo.college = data.imgInfo[0].college
        this.imgInfo.grade = data.imgInfo[0].grade
        this.imgInfo.usename = data.imgInfo[0].usename
        this.imgInfo.useID = data.imgInfo[0].useID
        this.exportShow = true;
      })
    },
    download(imgdata, type, filename) {
      //设置保存图片的类型
      //将mime-type改为image/octet-stream,强制让浏览器下载
      var fixtype = function(type) {
        type = type.toLocaleLowerCase().replace(/jpg/i, "jpeg");
        var r = type.match(/png|jpeg|bmp|gif/)[0];
        return "image/" + r;
      };
      imgdata = imgdata.replace(fixtype(type), "image/octet-stream");

      //将图片保存到本地
      var saveFile = function(data, filename) {
        var link = document.createElement("a");
        link.href = data;
        link.download = filename;
        var event = document.createEvent("MouseEvents");
        event.initMouseEvent( "click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null );
        link.dispatchEvent(event);
      };
      filename += "." + type;
      saveFile(imgdata, filename);
    },
    // saveFile (imgsrc, name) {
    //   let image = new Image();
    //   // 解决跨域 Canvas 污染问题
    //   image.setAttribute("crossOrigin", "anonymous");
    //   image.onload = function () {
    //     let canvas = document.createElement("canvas");
    //     canvas.width = image.width;
    //     canvas.height = image.height;
    //     let context = canvas.getContext("2d");
    //     context.drawImage(image, 0, 0, image.width, image.height);
    //     let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
    //     let a = document.createElement("a"); // 生成一个a元素
    //     let event = new MouseEvent("click"); // 创建一个单击事件
    //     a.download = name || "photo"; // 设置图片名称
    //     a.href = url; // 将生成的URL设置为a.href属性
    //     a.dispatchEvent(event); // 触发a的单击事件
    //   }
    //   //将资源链接赋值过去，才能触发image.onload 事件
    //   image.src = imgsrc
    // },
  },
  mounted () {
    let userId = this.$store.state.userId;
    if(!userId) return this.hasPhoto = false;
    this.hasPhoto = userId ? true : false
  }
};
</script>

<style>
@font-face {
  font-family: 'iconfont';  /* project id 2434445 */
  src: url('//at.alicdn.com/t/font_2434445_wltu26nr5dl.eot');
  src: url('//at.alicdn.com/t/font_2434445_wltu26nr5dl.eot?#iefix') format('embedded-opentype'),
  url('//at.alicdn.com/t/font_2434445_wltu26nr5dl.woff2') format('woff2'),
  url('//at.alicdn.com/t/font_2434445_wltu26nr5dl.woff') format('woff'),
  url('//at.alicdn.com/t/font_2434445_wltu26nr5dl.ttf') format('truetype'),
  url('//at.alicdn.com/t/font_2434445_wltu26nr5dl.svg#iconfont') format('svg');
}

.nav-bar {
  display: flex;
  flex-direction: row;
  position: relative;
  z-index: 999;
  justify-content: space-between;
  width: 100vw;
  height: 46px;
  line-height: 46px;
  background-color: #fff;
}

.nav-bar .nav-bar-left {
  color: #666;
  line-height: 46px;
  font-size: 20px;
  padding-top: 3px;
  margin-left: 15px;
}

.nav-bar .nav-bar-left:active,
.nav-bar .nav-bar-right i:nth-of-type(1):active,
.nav-bar .nav-bar-right i:nth-of-type(2):active {
  opacity: .3;
}

.nav-bar .nav-bar-right {
  color: #4662D9;
  transition: all .3s;
  line-height: 46px;
  margin-right: 15px;
}

.iconfont{
    font-family:"iconfont" !important;
    font-size:22px;
    font-style:normal;
    color: #666;
    -webkit-font-smoothing: antialiased;
    -webkit-text-stroke-width: 0.2px;
    -moz-osx-font-smoothing: grayscale;
}

.nav-icon {
  padding: 0 10px;
}

#photo-app {
  background-color: #EAEAEA;
  overflow: hidden;
  touch-action: none;
  height: 100vh;
}

.index-img-box {
  display: flex;
  height: 100%;
  flex-direction: row;
  padding: 10px;
  justify-content: space-between;
  align-items: center;
}

.index-img {
  width: 50%;
  margin-left: 10px;
}

.index-img-info {
  flex: 1;
  padding-left: 30px;
  border-right: 1px solid #ddd;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  height: 100%;
}

.index-img-info div {
  margin-top: 15px;
}

</style>
